#include "URAT.h"

DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
HANDLE hSerial;  // 串口句柄

int Open_URAT(char *com) {
	// 打开串口
	hSerial = CreateFile(com, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (hSerial == INVALID_HANDLE_VALUE) {
		printf("无法打开 %s\n", com);
		return -1;
	}
	return 1;
}

void URAT_Config(void) {
	// 配置串口
	dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
	GetCommState(hSerial, &dcbSerialParams);
	dcbSerialParams.BaudRate = CBR_115200;
	dcbSerialParams.ByteSize = 8;
	dcbSerialParams.StopBits = ONESTOPBIT;
	dcbSerialParams.Parity = NOPARITY;
	SetCommState(hSerial, &dcbSerialParams);

	// 设置超时
	timeouts.ReadIntervalTimeout = 50;
	timeouts.ReadTotalTimeoutConstant = 50;
	timeouts.ReadTotalTimeoutMultiplier = 10;
	timeouts.WriteTotalTimeoutConstant = 50;
	timeouts.WriteTotalTimeoutMultiplier = 10;
	SetCommTimeouts(hSerial, &timeouts);
}

// 串口发送函数
//void sendData(char data) {
void sendData(char *data) {
	DWORD bytesWritten;

	//EnterCriticalSection(&cs); // 保证线程安全写
	if (!WriteFile(hSerial, data, strlen(data), &bytesWritten, NULL)) {
		printf("发送失败\n");
	} else {
		printf("发送数据：%s", data);
	}
}

